package com.ckf.login_wx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckf.login_wx.entity.Log;
import com.ckf.login_wx.entity.User;
import com.ckf.login_wx.servic.LogService;
import com.ckf.login_wx.servic.UserService;
import com.ckf.login_wx.util.HttpContextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;




@RestController
@RequestMapping("/Sp")
public class SpLoginController {

    /**
     * 登录
     * @param phone
     * @param password
     * @return
     */
	@Autowired
    private UserService userService;
	
	@RequestMapping("/Login")
    public Map<String, Object> Login(HttpServletRequest request,HttpServletResponse response,String username, String password){
	    	
		Map<String, Object> map = new HashMap<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        mapuser.put("UserName", username);
        mapuser.put("Password",password);
        queryWrapper.allEq(mapuser);
        User a=userService.getOne(queryWrapper);
        if (a!=null){
        	Cookie cookie2 = new Cookie("username", a.getQuxianname()+":"+username);
        	cookie2.setMaxAge(100*60*60);  
            cookie2.setPath("/");  
        	response.addCookie(cookie2);
        	Cookie[] cookies = request.getCookies();  
            if (cookies!=null) {   
                for(Cookie cookie : cookies){  
                    if(cookie.getName().equals("username")){  
                        cookie.setValue(a.getQuxianname()+":"+a.getTruename());  
                        cookie.setPath("/");  
                        cookie.setMaxAge(100*60*60);
                        System.out.println("写入cookie");
                        response.addCookie(cookie);
                        break;  
                    } 
                }
            } 
//        	Cookie cookie = new Cookie("username", "");
//        	cookie.setMaxAge(0);
//        	response.addCookie(cookie);
        	
        	
        	HttpSession session= request.getSession();
			session.setAttribute("username", username);
			session.setAttribute("password", password);
			session.setAttribute("quxian", a.getQuxian());
			session.setAttribute("quxianname", a.getQuxianname());
			session.setAttribute("truename", a.getTruename());
            map.put("code",200);
            map.put("username",username);
            map.put("quxian",a.getQuxian());
            map.put("result","登录成功");
            System.out.println("登录成功");
        }else {
            map.put("result","密码错误");
            map.put("code",200);
        }
        return map;
    }
	@RequestMapping("/outlogin")
    public void outlogin(HttpServletRequest request,HttpServletResponse response){
		Cookie[] cookies = request.getCookies();  
        if (null==cookies) {  
            System.out.println("没有cookie==============");  
        } else {  
            for(Cookie cookie : cookies){  
                if(cookie.getName().equals("username")){  
                    cookie.setValue("");  
                    cookie.setPath("/");  
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);  
                    break;  
                }  
            }  
        } 
		HttpSession session= request.getSession();
		session.invalidate();
		System.out.println("outlogin");
	}
	@RequestMapping("/selepwdbyuser")
    public boolean selepwdbyuser(String username, String password){

		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
	    Map<String, Object> mapuser = new HashMap<>();
	    mapuser.put("username",username);
	    mapuser.put("password",password);
	    queryWrapper.allEq(mapuser);
		List<User> a= userService.list(queryWrapper);
		if(a.size()==0){
			return false;
			//return "密码错误！";
		}else{
			return true;
			//return "密码验证成功！";
		}
	}
	@RequestMapping("/upuser")
    public boolean upuser(String user, String password, String newpassword){
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
	    Map<String, Object> mapuser = new HashMap<>();
	    mapuser.put("username",user);
	    mapuser.put("password",password);
	    queryWrapper.allEq(mapuser);
		List<User> a= userService.list(queryWrapper);
		if(a.size()==1){
			User userone=a.get(0);
			userone.setPassword(newpassword);
			if(userService.updateById(userone)){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	@RequestMapping("upload")
	public Object uploadimg(MultipartFile file,String name) {//,String name
    	Map<String, Object> map = new HashMap<>();
		System.out.println("***********上传图片**********"+name);
    	
		// 获取原始名字
		String fileName = file.getOriginalFilename();
		// 获取后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		// 文件保存路径
		String filePath = "c:/springboot_installl/img/";

		// 文件重命名，防止重复
		//String uuid=""+UUID.randomUUID();uuid=uuid.substring(2, 6);
		String uuid=name;
		String img=uuid+"@"+fileName;
		fileName = filePath+img;
		File dest = new File(fileName);
		// 判断路径是否存在，如果不存在则创建
		if(!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			// 保存到服务器中
			file.transferTo(dest);
			map.put("code",0);
	        map.put("data",null);
	        map.put("msg",img);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code",0);
	        map.put("data",null);
	        map.put("msg","保存失败");
			return map;
		}
	}
	@RequestMapping(value = "/gettu",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(String name) throws IOException {
		//System.out.println(name+"初始接收**********************************************************");
		//name="Image/"+name.substring(6);
		//C:/springboot_installl/img/11.png
		name="C:/springboot_installl/img/"+name;
		try{
	        File file = new File(name);
			FileInputStream inputStream = new FileInputStream(file);
	        byte[] bytes = new byte[inputStream.available()];
	        inputStream.read(bytes, 0, inputStream.available());
	        return bytes;
	    }catch(FileNotFoundException e){
	    	return null;
	    }
    }
	@RequestMapping("/")
    public void jy2021(HttpServletResponse response) throws IOException{
		response.sendRedirect("login.html");
        //return "jy2021";
    }
}






